"""
Case Type   : bugfix
Case Name   : show grants for 支持user@host方式
Create At   : 2025/6/12
Owner       : liu-tong-8848
Description :
    1、打开b_compatibility_user_host_auth
    2、创建用户
    3、验证show grants for 支持user@host方式
    4、清理环境
Expect      :
    1、成功
    2、成功
    3、成功
    4、成功
History     :
"""

import os
import unittest

from yat.test import Node
from yat.test import macro

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class BugFix(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.common = Common()
        self.sh_primary = CommonSH('PrimaryDbBmode')
        self.user_node = Node('PrimaryDbBmode')
        self.constant = Constant()

    def test_dolphin(self):
        self.log.info(f'----{os.path.basename(__file__)} start----')
        text = '----step1:打开b_compatibility_user_host_auth；' \
               + 'expect:成功----'
        self.log.info(text)
        sql_cmd = "show b_compatibility_user_host_auth; set b_compatibility_user_host_auth to on; " \
                  + "drop user if exists 'u_fix_104'@'%'; create user 'u_fix_104'@'%' identified by 'test-1234'; " \
                  + "show grants for 'u_fix_104'@'%';"
        self.log.info(sql_cmd)
        sql_res = self.sh_primary.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertIn(self.constant.SET_SUCCESS_MSG, sql_res, '执行失败' + text)

        text = '----step2:创建用户；expect:成功----'
        self.log.info(text)
        self.assertIn(self.constant.DROP_ROLE_SUCCESS_MSG, sql_res, '执行失败' + text)
        self.assertIn(self.constant.CREATE_ROLE_SUCCESS_MSG, sql_res, '执行失败' + text)

        text = '----step3:验证show grants for 支持user@host方式；expect:成功----'
        self.log.info(text)
        self.assertIn("ALTER USER u_fix_104@'%' WITH LOGIN", sql_res, '执行失败' + text)
        self.assertIn("(1 row)", sql_res, '执行失败' + text)
        self.assertNotIn("ERROR", sql_res, '执行失败' + text)

    def tearDown(self):
        text = '----step4:清理环境；expect:成功----'
        self.log.info(text)
        sql_cmd = "set b_compatibility_user_host_auth to on; drop user if exists 'u_fix_104'@'%'; " \
                  + "set b_compatibility_user_host_auth to off;"
        self.log.info(sql_cmd)
        sql_res = self.sh_primary.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertIn(self.constant.SET_SUCCESS_MSG, sql_res, '执行失败' + text)
        self.assertIn(self.constant.DROP_ROLE_SUCCESS_MSG, sql_res, '执行失败' + text)
        self.log.info(f'----{os.path.basename(__file__)} end-----')
